package com.example.studentgrades.controller;


import com.example.studentgrades.dao.StudentDAO;
import com.example.studentgrades.model.Student;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/student/*")
public class StudentServlet extends BaseServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pathInfo = request.getPathInfo();

        if (pathInfo.equals("/register")) {
            register(request, response);
        } else if (pathInfo.equals("/login")) {
            login(request, response);
        } else if(pathInfo.equals("/logout")){
            logout(request,response);
        }
        // 可以添加更多操作的处理，比如成绩查询、信息修改等
    }

    private void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        Student student = new Student(username, password);

        try (Connection connection = getConnection()) {
            StudentDAO studentDAO = new StudentDAO(connection);
            studentDAO.addStudent(student);
            redirectToPage(response, "login.jsp"); // 注册成功后跳转到登录页面
        } catch (SQLException e) {
            handleSQLException(response, e, "register.jsp"); // 注册失败返回注册页面
        }
    }

    private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        try (Connection connection = getConnection()) {
            StudentDAO studentDAO = new StudentDAO(connection);
            Student student = studentDAO.findStudentByUsernameAndPassword(username, password);
            if (student != null) {
                HttpSession session = request.getSession();
                session.setAttribute("student", student);
                redirectToPage(response, "student_home.jsp"); // 登录成功后跳转到学生首页
            } else {
                redirectToPage(response, "login.jsp"); // 登录失败返回登录页面
            }
        } catch (SQLException e) {
            handleSQLException(response, e, "login.jsp"); // 登录失败返回登录页面
        }
    }
    private void logout(HttpServletRequest request, HttpServletResponse response) throws  IOException {
        HttpSession session = request.getSession();
        session.removeAttribute("student");
        redirectToPage(response, "login.jsp"); // 登录成功后跳转到学生首页

    }
}

